
function kth(k,row1,w,gp,np,hi,lo,d,all,out,	\
	     row2,n,sorted,i,delta) {
    for(i in all) {
	row2=all[i]
	if (row2==row1) continue
	delta[i]["="]= row2
	delta[i]["x"]= dist(row1,row2,w,gp,np,hi,lo,d)
    }
    n=asort(delta,sorted,"xsort")
    if (n <  k) k = n
    for(i=1;i<=k;i++)
	out[i]= sorted[i]["="]
    return k
}
function dist(row1,row2,w,gp,np,hi,lo,d,\
              col,sum,ws,w1,x,y) {
    if (row1==row2) 
	return 0
    for(col in np) {
	if (gp[col]) continue
	w1 = w[col]; 
	if (w1==0) continue
	x  = d[row1][col]
	y  = d[row2][col]
	if (x=="?" && y=="?") continue 
	sum += w1 * dist1(x,y,col,np,hi,lo)
	ws  += w1
    }
    return sqrt(sum)/sqrt(ws + 0.000001)
}

function dist1(x,y,col,np,hi,lo,d) {
    if (x == y) 
	return 0
    if (!np[col])  
	return value(x) != value(y)
    if (y == "?") {
	x  = norm(x,col,hi,lo)
	y  = x > 0.5 ? 0 : 1
    } else if (x == "?") {
	y = norm(y,col,hi,lo)
	x = y > 0.5 ? 0 : 1
    } else {
	x = norm(x,col,hi,lo)
	y = norm(y,col,hi,lo)
    } 
    return  (x - y)^2 
}
function norm(x,col,hi,lo) {
    if (Normalize)
	return (x - lo[col])/(hi[col] - lo[col] +0.00001)
    else
	return x
}
function value(x) {
    return x=="?" ? "SomeCrazySyMBOL" : x
}